# _*_ coding:utf-8 _*_
# @File  : client_op.py
# @Time  : 2021-06-10 15:05
# @Author: zizle
import datetime

from fastapi import APIRouter, Depends, Query, Body, Path
from pydantic import BaseModel
from db import FAConnection
from interfaces.depends import admin_logged_require
from category import CLIENTS
from status import r_status
from hutool.utils import list2tree

op_client_api = APIRouter()


@op_client_api.get('/client/', summary='分页获取客户端列表')
async def get_clients(person: dict = Depends(admin_logged_require), page: int = Query(..., ge=1),
                      page_size: int = Query(..., ge=20, le=100)):
    db = FAConnection(conn_name='Query Clients')
    start_record = (page - 1) * page_size
    offset_record = page_size
    query_sql = 'SELECT SQL_CALC_FOUND_ROWS id,create_time,update_time,client_name,disk,board,client_code,category,' \
                'user_login,resolution,is_active ' \
                'FROM sys_client ORDER BY update_time DESC LIMIT %s,%s;'
    records = db.query(query_sql, [start_record, offset_record], keep_conn=True)
    total_obj = db.query('SELECT FOUND_ROWS() AS total;', fetchone=True)
    total_count = total_obj[0]['total'] if total_obj else 0  # 当前总数量
    for item in records:
        item['create_time'] = item['create_time'].strftime('%Y-%m-%d %H:%M:%S')
        item['update_time'] = item['update_time'].strftime('%Y-%m-%d %H:%M:%S')
        item['category_name'] = CLIENTS.get(item['category'], '未知')
    return {'code': r_status.SUCCESS, 'message': '查询客户端列表成功!', 'data': records, 'page': page,
            'page_size': page_size, 'total_count': total_count}


@op_client_api.put('/client/{client_id}/', summary='修改客户端名称')
async def update_client_message(person: dict = Depends(admin_logged_require), client_id: int = Path(..., ge=0),
                                client_name: str = Body(..., embed=True), is_active: int = Body(..., embed=True)):
    update_sql = 'UPDATE sys_client SET client_name=%s,is_active=%s WHERE id=%s;'
    db = FAConnection(conn_name='修改客户端名称')
    _, success = db.execute(update_sql, [client_name, is_active, client_id])
    if success:
        return {'code': r_status.SUCCESS, 'message': '修改信息成功!'}
    return {'code': r_status.UNKNOWN_ERROR, 'message': '修改信息失败!'}


@op_client_api.get('/client.menus/', summary='获取一个客户端的所有菜单情况')
async def get_client_menus(person: dict = Depends(admin_logged_require),
                           client: str = Query(..., min_length=32, max_length=32)):
    db = FAConnection(conn_name='管理查询客户端菜单')
    sql = 'SELECT id,parent_id,category,icon,name_en,name_zh,sorted FROM sys_menu WHERE category=2 AND is_active=1;'
    records = db.query(sql, keep_conn=True)
    exclude_sql = 'SELECT id,menu_id,expire FROM sys_client_exclude_menu WHERE client_code=%s;'
    excludes = db.query(exclude_sql, [client])
    excludes_id = [m['menu_id'] for m in excludes]
    # 添加排除的记号
    now_str = datetime.datetime.now().strftime('%Y-%m-%d')
    for menu in records:
        menu['is_exclude'] = False
        menu['expire_date'] = ''
        for ex_item in excludes:
            expire_str = ex_item['expire'].strftime('%Y-%m-%d')
            if menu['id'] == ex_item['menu_id'] and expire_str >= now_str:
                menu['is_exclude'] = True
                menu['expire_date'] = expire_str
                break

    # 转为tree后返回
    rep_data = list2tree(records, 0)
    return {'code': r_status.SUCCESS, 'message': '获取客户端菜单成功!', 'data': rep_data}


class ExcludeMenuItem(BaseModel):
    client_code: str
    menu_id: int
    expire_date: str


@op_client_api.post('/client.menu/', summary='编辑一个客户端的菜单排除日期')
async def set_client_exclude_menu(person: dict = Depends(admin_logged_require),
                                  ex_item: ExcludeMenuItem = Body(...)):
    try:
        expire = datetime.datetime.strptime(ex_item.expire_date, '%Y-%m-%d')
    except ValueError:
        return {'code': r_status.VALIDATE_ERROR, 'message': '参数expire_date格式错误,需为%Y-%m-%d'}
    db = FAConnection(conn_name='设置客户端排除菜单')
    # 先查询该菜单的子菜单
    query_children = 'SELECT id,parent_id FROM sys_menu WHERE parent_id=%s;'
    children = db.query(query_children, [ex_item.menu_id], keep_conn=True)
    update_rows = [{'creator': person['uid'], 'client_code': ex_item.client_code, 'menu_id': ex_item.menu_id,
                    'expire': expire.strftime('%Y-%m-%d')}]
    for c_menu in children:
        update_rows.append({'creator': person['uid'], 'client_code': ex_item.client_code, 'menu_id': c_menu['id'],
                            'expire': expire.strftime('%Y-%m-%d')})
    # 先插入数据
    insert_sql = 'INSERT IGNORE sys_client_exclude_menu (creator,client_code,menu_id,expire) ' \
                 'VALUES (%(creator)s,%(client_code)s,%(menu_id)s,%(expire)s);'
    count, _ = db.insert(insert_sql, param=update_rows, many=True, keep_conn=True)
    if count == 0:
        db.correct_table_auto_increment(table_name='sys_client_exclude_menu')
    # 再更新数据
    update_sql = 'UPDATE sys_client_exclude_menu SET creator=%(creator)s,expire=%(expire)s ' \
                 'WHERE menu_id=%(menu_id)s AND client_code=%(client_code)s;'
    _, success = db.execute(update_sql, param=update_rows, many=True)
    if success:
        return {'code': r_status.SUCCESS, 'message': '操作成功!'}
    return {'code': r_status.SUCCESS, 'message': '操作失败,原因未知!'}


@op_client_api.get('/client/suggest/', summary='获取客户端建议列表')
async def client_suggest(person: dict = Depends(admin_logged_require), page: int = Query(..., ge=1),
                         page_size: int = Query(..., ge=20, le=100)):
    record_start = (page - 1) * page_size
    record_offset = page_size
    sql = 'SELECT SQL_CALC_FOUND_ROWS a.id,a.create_time,a.author_id,b.username,a.suggest,a.parent_id ' \
          'FROM sys_user_suggest AS a ' \
          'INNER JOIN user_user AS b ON a.author_id=b.id ' \
          'ORDER BY a.create_time DESC LIMIT %s,%s;'
    db = FAConnection(conn_name='管理查询建议')
    records = db.query(sql, [record_start, record_offset], keep_conn=True)
    total_obj = db.query('SELECT FOUND_ROWS() AS total;', fetchone=True)
    total_count = total_obj[0]['total'] if total_obj else 0  # 当前总数量
    for r in records:
        r['create_time'] = r['create_time'].strftime('%Y-%m-%d %H:%M:%S')
    records = list2tree(records, 0)
    return {'code': r_status.SUCCESS, 'message': '查询建议记录!', 'page': page, 'page_size': page_size,
            'total_count': total_count, 'data': records}
